// =================================================================================================
//
//	CopyEngine Framework
//	Copyright 2012 Eran. All Rights Reserved.
//
//	This program is free software. You can redistribute and/or modify it
//	in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================

package copyengine.utils.math
{
	import flash.geom.Point;

	public final class BezierMathUtils
	{
		public function BezierMathUtils()
		{
		}

		/**
		 *取得某条直线AB的垂直平分线上的某一点坐标(偏移值根据AB两点之间距离的百分比计算)
		 *
		 * @param _aX     				点A的X坐标
		 * @param _aY					点A的Y坐标
		 * @param _bX					点B的X坐标
		 * @param _bY					点B的Y坐标
		 * @param _offsetPercent		AB的距离的百分比(作为Offset的偏移值)
		 * @param _resultPointA			得到的结果点A
		 * @param _resultPointB			得到的结果点B
		 *
		 */
		public static function calculateABLinePerpendicularBisectorPointByOffsetPercent(_aX:Number,
																						_aY:Number,
																						_bX:Number,
																						_bY:Number,
																						_offsetPercent:Number,
																						_resultPointA:Point,
																						_resultPointB:Point):void
		{
			var offsetSquare:Number=((_bX - _aX) * (_bX - _aX) + (_bY - _aY) * (_bY - _aY)) * _offsetPercent * _offsetPercent;
			calculateABLinePerpendicularBisectorPoint(_aX, _aY, _bX, _bY, offsetSquare, _resultPointA, _resultPointB);
		}



		/**
		 *取得某条直线AB的垂直平分线上的某一点坐标</br>
		 *详细推导参见 http://git.oschina.net/eran/BezierMathUtils
		 *
		 * @param _aX     				点A的X坐标
		 * @param _aY					点A的Y坐标
		 * @param _bX					点B的X坐标
		 * @param _bY					点B的Y坐标
		 * @param _offsetSquare			在垂直平分线上和AB直线中点之间距离的偏移值的平方
		 * @param _resultPointA			得到的结果点A
		 * @param _resultPointB			得到的结果点B
		 *
		 */
		public static function calculateABLinePerpendicularBisectorPoint(_aX:Number,
																		 _aY:Number,
																		 _bX:Number,
																		 _bY:Number,
																		 _offsetSquare:Number,
																		 _resultPointA:Point,
																		 _resultPointB:Point):void
		{
			if (_aY != _bY)
				//_aY 如果等于 _bY 则 _bY - _aY相减为0 函数出现除0情况
			{
				var A:Number=(_aY + _bY) / 2 - (_aX - _bX) * (_aX + _bX) / (2 * (_bY - _aY));
				var B:Number=(_aX - _bX) / (_bY - _aY);
				var E:Number=(_bX + _aX) / 2;
				var F:Number=(_bY + _aY) / 2;
				var G:Number=B * B + 1;
				var H:Number=2 * (A * B - E - B * F);
				var I:Number=_offsetSquare - E * E - (F - A) * (F - A);

				_resultPointA.x=(Math.sqrt(H * H + 4 * G * I) - H) / (2 * G);
				_resultPointB.x=(-Math.sqrt(H * H + 4 * G * I) - H) / (2 * G);

				_resultPointA.y=B * _resultPointA.x + A;
				_resultPointB.y=B * _resultPointB.x + A;
			}
			else
			{
				//如果_aY == _bY 则直线平行于屏幕
				_resultPointA.x=_resultPointB.x=(_bX + _aX) / 2;
				_resultPointA.y=_aY - Math.sqrt(_offsetSquare);
				_resultPointB.y=_aY + Math.sqrt(_offsetSquare);
			}

		}


	}
}
